package fileController

import (
	"bookStore/util/contextUtils"
	"github.com/gin-gonic/gin"
	"net/http"
	"os"
)

var filePath = "./file/"

// 单文件或多文件上传
func FileUpload(ctx *gin.Context) {
	form, err := ctx.MultipartForm()
	if err != nil {
		contextUtils.ErrorJSON(ctx, http.StatusBadRequest, err.Error())
	} else {
		files := form.File["file"]
		if files == nil || len(files) == 0 {
			contextUtils.ErrorJSON(ctx, http.StatusBadRequest, "缺少file字段或没有指定文件")
		} else {
			fileNames := make([]string, 0)
			for _, file := range files {
				ctx.SaveUploadedFile(file, filePath+file.Filename)
				fileNames = append(fileNames, file.Filename)
			}
			contextUtils.OkJSON(ctx, fileNames)
		}
	}
}

func FileDownload(ctx *gin.Context) {
	fileName := ctx.Query("fileName")
	pathName := filePath + fileName
	file, err := os.Open(pathName)
	if file != nil {
		defer file.Close()
	}
	if err != nil {
		contextUtils.ErrorJSON(ctx, http.StatusInternalServerError, err.Error())
	} else {
		ctx.Header("Content-Type", "application/octet-stream")
		ctx.Header("Content-Disposition", "attachment; filename="+fileName)
		ctx.Header("Content-Transfer-Encoding", "binary")
		ctx.File(pathName)
	}
}
